<template>
  <div class="page">
    <!-- 搜索区域 开始 -->
    <div class="el_card_box">
      <el-form :inline="true" size="small" :model="formInline" class="search_form">
        <el-form-item label="预约时间：">
          <el-date-picker v-model="formInline.orderTime" type="daterange" unlink-panels :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="报名时间：">
          <el-date-picker v-model="formInline.applyTime" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="创建时间：">
          <el-date-picker v-model="formInline.createTime" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约城市：">
          <!-- <el-select v-model="formInline.city" @change="getHospital" filterable clearable>
            <el-option v-for="(item,index) in cityList" :key="index" :label="item.name" :value="item.code"></el-option>
          </el-select> -->
          <city-select v-model="formInline.cities" @change="getHospital"></city-select>
        </el-form-item>
        <el-form-item label="预约医院：">
          <el-select v-model="formInline.hospital" filterable clearable>
            <el-option v-for="(item,index) in hospitalList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约状态：">
          <el-select v-model="formInline.orderStatus" clearable>
            <el-option v-for="(item,index) in BOOKSTATUSLIST" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户需求：">
          <!-- <el-select v-model="formInline.project" clearable>
            <el-option v-for="(item,index) in projectList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select> -->
          <project-select v-model="formInline.projects"></project-select>
        </el-form-item>
        <el-form-item label="是否回访：">
          <el-select v-model="formInline.returnVisit" clearable>
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="负责人：">
          <!-- <el-select v-model="formInline.principal" filterable clearable>
            <el-option v-for="(item,index) in userList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select> -->
          <user-select v-model="formInline.principals"></user-select>
        </el-form-item>
        <el-form-item label="客户来源：">
          <user-source v-model="formInline.clueSources"></user-source>
        </el-form-item>
        <el-form-item label="广告代号：">
          <!-- <el-select v-model="formInline.adSource" filterable clearable>
            <el-option v-for="(item,index) in adCodeList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select> -->
          <adcode-select v-model="formInline.adSources"></adcode-select>
        </el-form-item>
        <el-form-item label="是否提醒：">
          <el-select v-model="formInline.remindStatus" clearable>
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门：">
          <depart-ment v-model="formInline.departmentId"></depart-ment>
        </el-form-item>
        <el-form-item label="客户标签：">
          <tag-select v-model="formInline.tags" filter></tag-select>
        </el-form-item>
        <el-form-item label="关键词：">
          <el-input v-model="formInline.term" placeholder="请输入客户姓名/电话" @keyup.enter.native="getList(1)"></el-input>
        </el-form-item>
      </el-form>
      <div class="search_btn_box">
        <el-button type="primary" size="small" @click="onSearch">筛选</el-button>
        <el-button type="default" size="small" @click="rest">清空筛选</el-button>
      </div>
    </div>
    <!-- 搜索区域 end -->

    <!-- 表格 开始 -->
    <div class="table_box">
      <!-- 操作区域 开始 -->
      <div class="action_box">
        <el-button type="primary" size="small" @click="openBookDialog()">新增预约</el-button>
        <!-- <el-button type="default" size="small" :loading="eloading" @click="downloadExcel">导出筛选结果</el-button> -->
        <auth-button uid="1030101" type="default" size="small" :loading="eloading" @click.native="downloadExcel()" v-if="status == 0">导出筛选结果</auth-button>
        <auth-button uid="1030201" type="default" size="small" :loading="eloading" @click.native="downloadExcel()" v-if="status == 1">导出筛选结果</auth-button>
        <auth-button uid="1030301" type="default" size="small" :loading="eloading" @click.native="downloadExcel()" v-if="status == 2">导出筛选结果</auth-button>
        <auth-button uid="1030401" type="default" size="small" :loading="eloading" @click.native="downloadExcel()" v-if="status == 3">导出筛选结果</auth-button>
        <auth-button uid="1030103" type="default" size="small" :loading="eloading" @click.native="downloadExcel(1)" v-if="status == 0">批量导出非脱敏记录</auth-button>
      </div>
      <!-- 操作区域 end -->

      <el-table ref="elTable" class="el_table" size="small" :data="tableData" @sort-change="sortChange">
        <!-- <el-table-column type="selection" width="55" /> -->
        <el-table-column prop="channelName" label="客户信息" width="150px">
          <template slot-scope="{row}">
            <tab-user :user="userFormatter(row)"></tab-user>
          </template>
        </el-table-column>
        <el-table-column prop="downloadCnt" label="客户需求">
          <template slot-scope="{row}">
            <div class="tag_list">
              <div class="tag" v-for="(item,index) in (row.enrollProject?row.enrollProject.split(','):[])" :key="index">{{item}}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="registerCnt" label="年龄" width="80">
          <template slot-scope="{row}">{{row.age}}岁</template>
        </el-table-column>
        <!-- <el-table-column prop="enrollFee" label="报名费" width="80">
          <template slot-scope="{row}">{{row.enrollFee}}元</template>
        </el-table-column> -->
        <el-table-column prop="cpa" label="信息收集">
          <template slot-scope="{row}">
            <el-tooltip class="item" effect="dark" placement="top-start">
              <div slot="content" style="max-width:240px">{{row.collectInfo}}</div>
              <div class="tab_txt">{{row.collectInfo}}</div>
            </el-tooltip>
            <!-- <div class="tab_txt" :title="row.collectInfo">{{row.collectInfo}}</div> -->
          </template>
        </el-table-column>
        <el-table-column prop="hospitalName" label="预约医院" show-overflow-tooltip width="160px" />
        <el-table-column prop="appointmentTime" label="预约时间" sortable="custom" show-overflow-tooltip width="120">
          <template slot-scope="{row}">{{showTime(row.appointmentTime)}}</template>
        </el-table-column>
        <el-table-column prop="remark" label="预约备注">
          <template slot-scope="{row}">
            <el-tooltip class="item" effect="dark" placement="top-start">
              <div slot="content" style="max-width:240px">{{row.remark}}</div>
              <div class="tab_txt">{{row.remark}}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="statusDesc" label="预约状态" show-overflow-tooltip>
          <template slot-scope="{row}">
            <el-tooltip class="item" effect="dark" placement="top-start" v-if="(row.status == 7 || row.status == 6) && row.reason">
              <div slot="content" style="max-width:240px">{{row.reason}}</div>
              <div>{{row.statusDesc}} <i class="el-icon-warning-outline"></i></div>
            </el-tooltip>
            <span v-else>{{row.statusDesc}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="outpatientFeedback" label="门诊反馈">
          <template slot-scope="{row}">
            <el-tooltip class="item" effect="dark" placement="top-start">
              <div slot="content" style="max-width:240px">{{row.outpatientFeedback}}</div>
              <div class="tab_txt">{{row.outpatientFeedback}}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="remindStatus" label="是否提醒" show-overflow-tooltip>
          <template slot-scope="{row}">{{row.remindStatus == 1?'是':'否'}}</template>
        </el-table-column>
        <el-table-column prop="returnVisitCnt" label="是否回访" show-overflow-tooltip>
          <template slot-scope="{row}">{{row.returnVisitCnt>0?'是':'否'}}</template>
        </el-table-column>
        <el-table-column prop="principal" label="负责人" show-overflow-tooltip />
        <el-table-column prop="address" label="操作" width="240px" align="center" fixed="right">
          <template slot-scope="{row}">
            <el-link type="primary" class="el_link" v-if="status == 1" :underline="false" @click="remindEvent(row)">提醒</el-link>
            <template v-if="row.status == 6 || row.status == 4 || row.status == 8">
              <el-link type="primary" class="el_link" :underline="false" @click="openDialog('shopVisitDialog',row)">回访</el-link>
            </template>
            <template v-if="row.status == 7">
              <el-link type="primary" class="el_link" :underline="false" @click="openDialog('shopVisitDialog',row)">回访</el-link>
              <el-link type="primary" class="el_link" :underline="false" @click="openDialog('shopDialog',row)">修改成交</el-link>
            </template>
            <template v-if="row.status == 5">
              <el-link type="primary" class="el_link" :underline="false" :id="row.id" @click="openDialog('cancelDialog',row)">取消</el-link>
              <el-link type="primary" class="el_link" :underline="false" :id="row.id" @click="openBookDialog(row)">改约</el-link>
              <el-link type="primary" class="el_link" :underline="false" @click="openDialog('shopDialog',row)">到店</el-link>
              <el-link type="primary" class="el_link" :underline="false" @click="openDialog('shopVisitDialog',row)">回访</el-link>
            </template>
            <template v-if="row.status == 1 || row.status == 2||row.status == 3">
              <el-link type="primary" class="el_link" :underline="false" :id="row.id" @click="openDialog('cancelDialog',row)">取消</el-link>
              <el-link type="primary" class="el_link" :underline="false" :id="row.id" @click="openBookDialog(row)">改约</el-link>
              <el-link type="primary" class="el_link" :underline="false" @click="openDialog('shopDialog',row)">到店</el-link>
              <el-link type="primary" class="el_link" :underline="false" @click="openDialog('shopVisitDialog',row)">回访</el-link>
              <el-link type="primary" class="el_link" :underline="false" @click="openDialog('shopDialog',row)">修改成交</el-link>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination_list">
        <el-pagination background layout="sizes, total,prev, pager, next, jumper" :total="pageTotal" :page-size="pageSize" :page-sizes="pageSizes" :current-page.sync="pageNumber" @current-change="getList" @size-change="changePageSize" />
      </div>
    </div>
    <!-- 表格 end -->

    <!-- 新增预约 开始 -->
    <!-- <glsx-dialog :show="bookDialog" :title="dialogTitle" width="60%" @close="closeDialog('bookDialog')">
      <div class="">
        <add-book ref="addBookCom" :id="customerInfo.id" :info="bookInfo" v-if="bookDialog" @change="onChange"></add-book>
      </div>
      <div slot="footer">
        <el-button type="primary" size="small" :loading="loading" @click="saveInfo()">提交预约</el-button>
        <el-button type="default" size="small" @click="closeDialog('bookDialog')">取消</el-button>
      </div>
    </glsx-dialog> -->
    <!-- 新增预约 end -->

    <!-- 取消预约 开始 -->
    <glsx-dialog :show="cancelDialog" title="取消预约" @close="closeDialog('cancelDialog')">
      <el-form size="small" label-width="100px">
        <el-form-item label="姓名：" required>
          <span>{{customerInfo.name}}/{{customerInfo.phone}}</span>
        </el-form-item>
        <el-form-item label="预约城市：" required>
          <span>{{customerInfo.city}}</span>
        </el-form-item>
        <el-form-item label="预约医院：" required>
          <span>{{customerInfo.hospitalName}}</span>
        </el-form-item>
        <el-form-item label="预约时间：" required>
          <span>{{customerInfo.appointmentTime}}</span>
        </el-form-item>
        <el-form-item label="取消原因：" required>
          <el-input type="textarea" v-model="remark"></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" @click="cancelBook">取消预约</el-button>
        </el-form-item>
      </el-form>
    </glsx-dialog>
    <!-- 取消预约 end -->

    <!-- 已到店 开始 -->
    <glsx-dialog :show="shopDialog" title="客户到店更新" width="60%" @close="closeDialog('shopDialog')">
      <shop-update :info="customerInfo" @change="onChange" v-if="shopDialog"></shop-update>
    </glsx-dialog>
    <!-- 已到店 end -->

    <!-- 写回访 开始 -->
    <glsx-dialog :show="shopVisitDialog" title="客户到店回访" width="60%" @close="closeDialog('shopVisitDialog')">
      <shop-visit :info="customerInfo" @change="onChange" v-if="shopVisitDialog"></shop-visit>
    </glsx-dialog>
    <!-- 写回访 开始 -->

  </div>
</template>

<script>
import {
  GETCITYOPTIONS,
  GETPROJECTOPTIONS,
  GETUSEROPTIONS,
  GETADSOURCEOPTIONS,
} from "@/http/system";
import { GETHOSPITALOPTIONS } from "@/http/hospital";
import {
  GETORDERSEARCH,
  CANCELORDERINFO,
  ORDEREXPORT,
  ORDER_REMIND,
} from "@/http/book";
import {
  showToast,
  showModal,
  deepClone,
  broadcast,
  received,
} from "@/common/util";
import { exportExcel } from "@/common/common";
import GlsxDialog from "@/components/Dialog/index";
import GlsxTable from "@/components/glsx-table/index";
import AddBook from "../customer/addBook";
import CustomerDetail from "../customer/detail";
import ShopUpdate from "./update";
import ShopVisit from "./shopVisit";
import moment from "moment";
import TabUser from "@/components/user";
import { BOOKSTATUSLIST } from "@/common/constants";
import AuthButton from "@/components/auth-button";
import CitySelect from "@/components/select/city";
import ProjectSelect from "@/components/select/project";
import UserSelect from "@/components/select/user";
import AdcodeSelect from "@/components/select/adCode";
import UserSource from "@/components/select/source";
export default {
  name: "BookPage",
  props: {
    status: {
      type: [String, Number],
      default: 0,
    },
  },
  components: {
    GlsxDialog,
    GlsxTable,
    AddBook,
    CustomerDetail,
    ShopUpdate,
    ShopVisit,
    TabUser,
    AuthButton,
    CitySelect,
    ProjectSelect,
    AdcodeSelect,
    UserSelect,
    UserSource,
  },
  data() {
    return {
      formInline: {},
      tableData: [],
      pageTotal: 0,
      pageNumber: 1,
      pageSizes: [10, 20, 50, 100],
      pageSize: 20,
      eloading: false,
      orderTime: [],
      showDialog: false,
      loading: false,
      bookDialog: false,
      pickerOptions: {
        shortcuts: [
          {
            text: "前天",
            onClick(picker) {
              const end = moment().subtract(2, "days").format("YYYY-MM-DD");
              const start = moment().subtract(2, "days").format("YYYY-MM-DD");
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const end = moment().subtract(1, "days").format("YYYY-MM-DD");
              const start = moment().subtract(1, "days").format("YYYY-MM-DD");
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "今天",
            onClick(picker) {
              const end = moment().subtract(0, "days").format("YYYY-MM-DD");
              const start = moment().subtract(0, "days").format("YYYY-MM-DD");
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "明天",
            onClick(picker) {
              const end = moment().add(1, "days").format("YYYY-MM-DD");
              const start = moment().add(1, "days").format("YYYY-MM-DD");
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "后天",
            onClick(picker) {
              const end = moment().add(2, "days").format("YYYY-MM-DD");
              const start = moment().add(2, "days").format("YYYY-MM-DD");
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      cancelDialog: false,
      remark: "",
      dialogTitle: "新增预约",
      shopDialog: false,
      shopVisitDialog: false,
      customerInfo: {},
      bookInfo: {},
      cityList: [],
      projectList: [],
      userList: [],
      hospitalList: [],
      BOOKSTATUSLIST: BOOKSTATUSLIST,
      adCodeList: [],
    };
  },
  mounted() {
    let _this = this;
    let o = this.$route.query;
    if (o.orderStatus) {
      this.$set(this.formInline, "orderStatus", o.orderStatus);
    }
    this.getList();
    //this.getCity();
    //this.getProject();
    //this.getUser();
    this.getHospital();
    //this.getAdCodeList();
    received("commom.edit.success", _this.getList);
    received("customer.add.success", _this.getList);
  },
  methods: {
    /** 重置 */
    rest() {
      this.formInline = {};
      this.orderTime = [];
      this.getList();
    },

    /** 每页展示 */
    changePageSize(e) {
      this.pageSize = e;
      this.getList();
    },

    /** 获取参数 */
    getParams() {
      let oParams = JSON.parse(JSON.stringify(this.formInline));
      let n = oParams.orderTime;
      let m = oParams.applyTime;
      let k = oParams.createTime;

      if (n && n.length > 0) {
        oParams.orderStartTime = n[0];
        oParams.orderEndTime = n[1];
      } else {
        delete oParams.orderStartTime;
        delete oParams.orderEndTime;
      }

      if (m && m.length > 0) {
        oParams.enrollStartTime = m[0];
        oParams.enrollEndTime = m[1];
      }

      if (k && k.length > 0) {
        oParams.createdStartDate = k[0];
        oParams.createdEndDate = k[1];
      }

      delete oParams.orderTime;
      delete oParams.applyTime;
      delete oParams.createTime;

      oParams.pageNumber = this.pageNumber;
      oParams.pageSize = this.pageSize;
      oParams.pageType = this.status;
      return oParams;
    },

    /** 获取列表 */
    getList() {
      let _this = this;
      let oParams = this.getParams();
      GETORDERSEARCH(oParams).then((res) => {
        let obj = res.data || {};
        _this.tableData = obj.list || [];
        _this.pageTotal = obj.totalElements;
      });
    },

    // 导出excel
    downloadExcel(type) {
      let _this = this;
      let o = deepClone(_this.formInline);
      let m = Object.keys(o);
      if (m.length > 0) {
        showModal({
          message: "确定是否导出筛选条件下面所有预约列表?",
          showCancelButton: true,
          type: "warning",
          success: function () {
            _this.dowloadExcelFile(type);
          },
        });
        return false;
      }
      showToast({
        message: "请选择筛选条件后再导出",
      });
    },

    // 下载excel
    dowloadExcelFile(type) {
      let _this = this;
      let oParams = this.getParams();
      let options = {};
      if(type){
        oParams.desensitize = type;
      }
      options.method = "GET";
      options.data = oParams;
      options.url = ORDEREXPORT;
      options.fileName = "预约列表.xlsx";
      _this.eloading = true;
      exportExcel(options).then((res) => {
        _this.eloading = false;
      });
    },

    // 打开弹框
    openDialog(id, row) {
      this[id || "showDialog"] = true;
      if (id == "bookDialog" && row) {
        this.dialogTitle = "修改预约";
        // let o = {};
        // o.city = row.city
      }
      if (row) {
        this.customerInfo = row;
      }
    },

    // 关闭弹框
    closeDialog(id) {
      if (id == "bookDialog") {
        this.dialogTitle = "新增预约";
      }

      this[id || "showDialog"] = false;
      this.customerInfo = {};
    },

    // 保存客户信息
    saveInfo() {
      this.loading = true;
      this.$refs.addBookCom.saveInfo();
    },

    // 监听新增客户组件变化
    onChange(e) {
      let _this = this;
      _this.loading = false;
      if (e.id) {
        _this.closeDialog(e.id);
        _this.getList();
      }

      // 关闭当前弹框，再打开一个
      if (e.openId) {
        setTimeout(function () {
          _this.openDialog(e.openId);
          _this.customerInfo = e.oInfo;
        }, 100);
      }
    },

    // 取消预约
    cancelBook() {
      let _this = this;
      let txt = this.remark;
      if (!txt) {
        showToast({
          message: "请输入取消原因",
        });
        return false;
      }

      let oParams = {};
      oParams.orderId = this.customerInfo.id;
      oParams.cancelReason = txt;
      CANCELORDERINFO(oParams).then((res) => {
        if (res.code == 200) {
          showToast({
            message: "取消成功",
            type: "success",
          });
          _this.closeDialog("cancelDialog");
          _this.remark = "";
        }
      });
    },

    // 已到店
    updateInfo() {},

    // 格式化处理用户信息
    userFormatter(row) {
      let o = deepClone(row);
      o.customerName = o.name;
      o.customerPhone = o.phone;
      o.id = o.clueId;
      return o;
    },

    // 获取所有城市
    getCity() {
      GETCITYOPTIONS().then((res) => {
        this.cityList = res.data || [];
      });
    },

    // 获取所有项目
    getProject() {
      GETPROJECTOPTIONS().then((res) => {
        this.projectList = res.data || [];
      });
    },

    // 获取负责人列表
    getUser(name) {
      GETUSEROPTIONS({ username: name }).then((res) => {
        this.userList = res.data || [];
      });
    },

    // 获取所有医院
    getHospital(code) {
      let oParams = {};
      oParams.cities = code;

      if (this.formInline.hospital) {
        delete this.formInline.hospital;
      }

      GETHOSPITALOPTIONS(oParams).then((res) => {
        this.hospitalList = res.data || [];
      });
    },

    // 修改预约
    openBookDialog(row) {
      let oParams = {};
      if (row) {
        oParams.customerId = row.customerId;
        oParams.id = row.id;
      }
      broadcast("customer.add.book", oParams);
    },

    // 格式化展示时间
    showTime(str) {
      if (!str) {
        return "";
      }
      return moment(str).format("yyyy-MM-DD HH:mm");
    },

    // 获取广告代号
    getAdCodeList(id) {
      GETADSOURCEOPTIONS().then((res) => {
        this.adCodeList = res.data || [];
      });
    },

    // 监听表格排序
    sortChange({ column, prop, order }) {
      this.formInline.orderField = prop;
      if (order == "ascending") {
        this.formInline.orderDirection = "ASC";
      } else {
        this.formInline.orderDirection = "DESC";
      }
      this.getList();
    },

    // 提醒
    remindEvent(row) {
      let _this = this;
      showModal({
        message: "是否确认提醒?",
        showCancelButton: true,
        type: "warning",
        success: function () {
          let oParams = {};
          oParams.orderId = row.id;
          ORDER_REMIND(oParams).then((res) => {
            if (res.code != 200) {
              return false;
            }
            showToast({
              message: "操作成功",
              type: "success",
            });
            _this.getList();
          });
        },
      });
    },

    // 搜索
    onSearch(){
      this.pageNumber = 1;
      this.getList()
    }
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/style/customer/index.scss";
</style>
